﻿using AuthDemo.Data;
using OpenSourceCompany0405.Models;

namespace OpenSourceCompany0405.Services;

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

public class UserProcessingService : IHostedService, IDisposable
{
    private readonly ILogger<UserProcessingService> _logger;
    private readonly IServiceProvider _services;
    private Timer _timer;

    public UserProcessingService(
        ILogger<UserProcessingService> logger,
        IServiceProvider services)
    {
        _logger = logger;
        _services = services;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("用户处理服务已启动");
        
        // 设置每天凌晨2点执行（可根据需求调整时间间隔）
        _timer = new Timer(DoDailyWork, null, 
            TimeSpan.FromSeconds(10), // 首次立即执行（测试用）
            TimeSpan.FromHours(24));  // 实际生产环境用TimeSpan.FromDays(1)
        
        return Task.CompletedTask;
    }

    // 执行每天的任务
    private async void DoDailyWork(object state)
    {
        try
        {
            using var scope = _services.CreateScope();
            var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

            // 获取所有用户（可根据需求添加过滤条件）
            var users = await userManager.Users.ToListAsync();
            
            foreach (var user in users)
            {
                // 示例加工逻辑：自动补充用户名首字母大写
                if (!string.IsNullOrEmpty(user.FullName) && char.IsLower(user.FullName[0]))
                {
                    // 自动补充用户名首字母大写
                    ToUpperName(user);
                    // 初始化其段位
                    InitRank(users, user);
                    
                    await userManager.UpdateAsync(user);
                }

                // 添加其他处理逻辑...
            }

            await dbContext.SaveChangesAsync();
            _logger.LogInformation($"已处理 {users.Count} 个用户");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "用户处理任务执行失败");
        }
    }

    // 自动补充用户名首字母大写
    public void ToUpperName(ApplicationUser pUser)
    {
        pUser.FullName = char.ToUpper(pUser.FullName[0]) + pUser.FullName[1..];
    }
    
    // 初始化其段位
    public void InitRank(List<ApplicationUser> pUserList, ApplicationUser pUser)
    {
        if (pUser.HaveInitLevel == false)
        {
            // 配置StrategyLevel
            int tStrategyLevel = 0;
            InitOneRank(pUserList, pUser, ref tStrategyLevel);
            pUser.StrategyLevel = tStrategyLevel;
        
            // 配置TacticianLevel
            int tTacticianLevel = 0;
            InitOneRank(pUserList, pUser, ref tTacticianLevel);
            pUser.TacticianLevel = tTacticianLevel;
        
            // 配置WarriorLevel
            int tWarriorLevel = 0;
            InitOneRank(pUserList, pUser, ref tWarriorLevel);
            pUser.WarriorLevel = tWarriorLevel;
        
            // 配置完毕
            pUser.HaveInitLevel = true;
        }
    }

    public void InitOneRank(List<ApplicationUser> pUserList, ApplicationUser pUser, ref int pAutoLevel)
    {
        // 遍历所有用户段位，来填充当前段位
        
        // 先集合当前有效段位
        var rankList = new List<int>();
        foreach (var rank in pUserList)
        {
            if (rank.HaveInitLevel)
            {
                rankList.Add(pAutoLevel);
            }
        }
        
        // 从小到大排序
        rankList.Sort();

        // 根据段位等级来填充当前段位
        int tNowLevelMaxNum = 0;
        int tZeroLevelMaxNum = 6;
        int tNowLevel = 0;
        if (rankList.Count > 0)
        {
            int tMaxLevel = rankList[^1];
            // 遍历每个段位
            for(int tLevel = 0; tLevel <= tMaxLevel; tLevel++)
            {
                // 此段位最大人数量
                tNowLevelMaxNum = (int)((double)tZeroLevelMaxNum * Math.Pow(1.2d, tLevel));
                // 遍历rankList检测此段位是否已满
                int tHaveNum = 0;
                for (int tRankIndex = 0; tRankIndex < rankList.Count; tRankIndex++)
                {
                    if (rankList[tRankIndex] == tLevel)
                    {
                        tHaveNum++;
                    }
                }
                // 是否已满
                bool tIsFull = (tHaveNum >= tNowLevelMaxNum);
                if (!tIsFull)
                {
                    // 未满，设置当前段位
                    pAutoLevel = tLevel;
                    break;
                }
                
                // 全满了，最高段位+1
                if(tIsFull && tLevel == tMaxLevel - 1)
                {
                    // 已满，且已遍历到最高段位，设置当前段位为最高段位+1
                    pAutoLevel = tLevel + 1;
                    break;
                }
            }
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("用户处理服务已停止");
        _timer?.Change(Timeout.Infinite, 0);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}